package org.softmed.rest.server.xstream;

import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import com.thoughtworks.xstream.converters.Converter;
import com.thoughtworks.xstream.converters.MarshallingContext;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;

public class TimestampConverter implements Converter {

	SimpleDateFormat parser = new SimpleDateFormat();

	public TimestampConverter() {
		parser.applyPattern("dd-mm-yyyy HH:mm:ss.SSS");
	}

	@Override
	public void marshal(Object arg0, HierarchicalStreamWriter arg1,
			MarshallingContext arg2) {
		Timestamp ts = (Timestamp) arg0;
		String output = parser.format(ts);
		arg1.setValue(output);
	}

	@Override
	public Object unmarshal(HierarchicalStreamReader arg0,
			UnmarshallingContext arg1) {

		Date object = null;
		try {
			object = parser.parse(arg0.getValue());
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return new Timestamp(object.getTime());
	}

	@Override
	public boolean canConvert(Class arg0) {
		return arg0 == Timestamp.class;
	}

}
